#!/usr/bin/env python3
"""
Demo script for enhanced Ollama connection manager with robust error handling

This script demonstrates the key features implemented in Task 10:
1. Connection pooling and management
2. Health monitoring and metrics
3. Graceful degradation under load
4. Response validation for diff patches
5. Intelligent retry logic with adaptive timeouts
"""

import time
import logging
from fortran_commentator.managers.llm import LLMConnectionManager as OllamaConnectionManager

# Configure logging to show our enhancements in action
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def demo_connection_health_monitoring():
    """Demonstrate connection health monitoring and metrics"""
    print("\n=== Connection Health Monitoring Demo ===")
    
    # Initialize connection manager
    ollama = OllamaConnectionManager(
        base_url="http://60.245.128.27:11434",
        model_name="hopephoto/qwen3-30b-a3b-instruct_q8:latest",
        max_concurrent_connections=2
    )
    
    # Test connection and show health status
    print("Testing connection...")
    is_connected = ollama.test_connection()
    print(f"Connection successful: {is_connected}")
    
    # Display health metrics
    health = ollama.get_health_status()
    print("\nHealth Status:")
    for key, value in health.items():
        print(f"  {key}: {value}")

def demo_graceful_degradation():
    """Demonstrate graceful degradation under adverse conditions"""
    print("\n=== Graceful Degradation Demo ===")
    
    # Use a fake URL to simulate connection issues
    ollama = OllamaConnectionManager(
        base_url="http://fake.example.com:11434",
        model_name="test-model"
    )
    
    sample_fortran = """subroutine calculate_gradient(x, y, gradient)
  implicit none
  real, intent(in) :: x, y
  real, intent(out) :: gradient
  gradient = x * y + 2.0
end subroutine"""
    
    print("Attempting diff generation with unavailable model...")
    result = ollama.generate_diff_patch(
        "Add comments", sample_fortran, "test.f90"
    )
    
    print(f"Result: {result}")
    
    # Show how health degrades
    health = ollama.get_health_status()
    print(f"\nAfter failed attempts:")
    print(f"  is_connected: {health['is_connected']}")
    print(f"  consecutive_failures: {health['consecutive_failures']}")
    print(f"  is_degraded: {health['is_degraded']}")

def demo_response_validation():
    """Demonstrate response validation for diff patches"""
    print("\n=== Response Validation Demo ===")
    
    ollama = OllamaConnectionManager()
    
    # Test various diff responses
    test_cases = [
        ("Valid diff", "--- a/test.f90\n+++ b/test.f90\n@@ -1,3 +1,4 @@\n+!> @brief Test subroutine\n subroutine test\n   implicit none\n end subroutine"),
        ("Missing headers", "+!> @brief Test subroutine\n subroutine test"),
        ("Invalid format", "This is not a diff at all"),
        ("No comments", "--- a/test.f90\n+++ b/test.f90\n@@ -1,3 +1,4 @@\n+! Regular comment\n subroutine test")
    ]
    
    for description, diff_content in test_cases:
        is_valid, issues = ollama._validate_diff_response(diff_content, "test.f90")
        print(f"\n{description}:")
        print(f"  Valid: {is_valid}")
        if issues:
            print(f"  Issues: {issues}")

def demo_connection_pooling():
    """Demonstrate connection pooling and concurrent request handling"""
    print("\n=== Connection Pooling Demo ===")
    
    ollama = OllamaConnectionManager(max_concurrent_connections=2)
    
    print(f"Session pool size: {len(ollama.session_pool)}")
    
    # Simulate getting and returning sessions
    session1 = ollama._get_session()
    session2 = ollama._get_session()
    print(f"After getting 2 sessions, pool size: {len(ollama.session_pool)}")
    
    ollama._return_session(session1)
    ollama._return_session(session2)
    print(f"After returning sessions, pool size: {len(ollama.session_pool)}")

if __name__ == "__main__":
    print("Enhanced Ollama Connection Manager Demo")
    print("=" * 50)
    
    try:
        demo_connection_health_monitoring()
        demo_graceful_degradation()
        demo_response_validation()
        demo_connection_pooling()
        
    except Exception as e:
        logger.error(f"Demo error: {e}")
    
    print("\n=== Demo Complete ===")
    print("\nKey enhancements implemented in Task 10:")
    print("✅ Connection pooling for concurrent requests")
    print("✅ Health monitoring with success rate tracking")
    print("✅ Graceful degradation under adverse conditions")
    print("✅ Comprehensive response validation")
    print("✅ Intelligent retry logic with adaptive timeouts")
    print("✅ Detailed error handling for different failure modes")
    print("✅ Load tracking and concurrent request management")